﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skyhook.Core.Helpers
{
    public static class GCProfiler
    {
        static readonly int MaxGens = GC.MaxGeneration;
        static readonly StringBuilder Sb = new StringBuilder("GCs:");
        
        static int[] CollectionCounts;
        static bool HasChanged = false;

        static GCProfiler()
        {
            CollectionCounts = new int[MaxGens + 1];
            for (int i = 0; i < MaxGens; i++ )
            {
                CollectionCounts[i] = 0;
            }

            Sb.Remove(4, Sb.Length - 4);

            for (int i = 0; i <= MaxGens; i++)
            {
                Sb.Append(" Gen");
                Sb.Append(i);
                Sb.Append(":");
                Sb.Append(CollectionCounts[i]);
            }
        }

        public static StringBuilder GenerationsText
        {
            get
            {
                HasChanged = false;
                for (int i = 0; i <= MaxGens; i++)
                {
                    if (CollectionCounts[i] != GC.CollectionCount(i))
                    {
                        CollectionCounts[i] = GC.CollectionCount(i);
                        HasChanged = true;
                    }
                }

                if (HasChanged)
                {

                    Sb.Remove(4, Sb.Length - 4);

                    for (int i = 0; i <= MaxGens; i++)
                    {
                        Sb.Append(" Gen");
                        Sb.Append(i);
                        Sb.Append(":");
                        Sb.Append(GC.CollectionCount(i));
                    }
                }
                return Sb;
            }
        }
    }
}
